package com.plumejob.server.register;

import com.plumejob.server.register.cache.CacheManager;
import com.plumejob.server.register.constant.PlumeConstant;
import com.plumejob.server.register.dao.PlumeJobDao;
import com.plumejob.server.register.dao.PlumeJobLogDao;
import com.plumejob.server.register.dao.UserDao;
import com.plumejob.server.register.modal.PlumejobDetail;
import com.plumejob.server.register.pojo.PlumeJob;
import com.plumejob.server.register.pojo.PlumeJobLog;
import com.plumejob.server.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("plumejob")
@Slf4j
public class RegisterController {

    @Resource
    private UserDao userDao;
    @Resource
    private PlumeJobDao plumeJobDao;
    @Resource
    private PlumeJobLogDao plumeJobLogDao;


    @GetMapping("queryJobListByAppName")
    public R<PlumeJob> queryJobListByAppName(String appName) {
        List<PlumeJob> rows = plumeJobDao.findByAppName(appName);
        R<PlumeJob> res = new R<>();
        res.setDatas(rows);
        return res;
    }

    @GetMapping("heartBeat")
    public R<PlumejobExecutor> heartBeat(HttpServletRequest req, String appName) {
        String ip = IpUtils.getRealIp(req);
        String key = DigestUtils.md5DigestAsHex((appName + ip).getBytes());

        Set<String> plumejobExecutors = CacheManager.getData(appName);
        PlumejobExecutor plumejobExecutor = CacheManager.getData(key);

        if (plumejobExecutor == null) {
            plumejobExecutor = new PlumejobExecutor();
            plumejobExecutor.setExecutorIp(ip);
            plumejobExecutor.setMaster(PlumeConstant.STATUS_SLAVE);
        }
        if (plumejobExecutors == null) {
            plumejobExecutor.setMaster(PlumeConstant.STATUS_MASTER);
            plumejobExecutors = new HashSet<>();
        } else {
            int master = 0;
            for (String pjkey : plumejobExecutors) {
                PlumejobExecutor pj = CacheManager.getData(pjkey);
                if (pj != null && !pjkey.equals(key) && pj.getMaster().equals(PlumeConstant.STATUS_MASTER)) {
                    master++;
                    break;
                }
            }
            if (master == 0) {
                plumejobExecutor.setMaster(PlumeConstant.STATUS_MASTER);
            }
        }
        plumejobExecutors.add(key);
        CacheManager.setData(appName, plumejobExecutors);
        CacheManager.setData(key, plumejobExecutor, PlumeConstant.SURVIVAL_TIME);
        log.info("应用：{};地址：{};master:{}",appName,ip,plumejobExecutor.getMaster());
        return R.ok(plumejobExecutor);

    }

    @PostMapping("register")
    public R<Object> register(@RequestBody List<PlumeJob> jobs) {
        for (PlumeJob job : jobs) {
            int r = plumeJobDao.saveJob(job);
        }
        return R.OK;
    }

    @PostMapping("log")
    public R<Object> log(@RequestBody PlumejobDetail jd) {
        Date now = new Date();
        //1. update jobScheme
        plumeJobDao.updateScheme(jd);
        //2. insert log
        PlumeJobLog log = new PlumeJobLog();
        BeanUtils.copyProperties(jd, log);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        log.setPartitionField(dateFormat.format(now));
        plumeJobLogDao.insert(log);
        return R.OK;
    }

    @GetMapping("getRegister")
    public Object getRegister(String appName) {

        return true;
    }

    @GetMapping("findUser")
    public Object findUser(Integer id) {

        return userDao.findById(id);
    }
}
